package xu.ye.dao;

import java.util.ArrayList;
import java.util.List;

import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;

import com.agent.crm.bean.MyContact;
import com.agent.crm.db.DBInitScript;
import com.agent.crm.db.DatabaseManager;

public class ContactDao {
    private DatabaseManager manager = null;

    public ContactDao(Context cxt) {
        manager = new DatabaseManager(cxt);
    }

    public List<MyContact> getContactsByTypeId(int typeId) {
        SQLiteDatabase database = manager.getWritableDatabase();
        StringBuilder sqlStr = new StringBuilder();
        sqlStr.append("select c.contacts_id ,c.name,c.mobile_phone");
        sqlStr.append(" from " + DBInitScript.Table_ContactsInfo + " c");
        sqlStr.append(" where exists (select 1 from " + DBInitScript.Table_Type_Middle + " tm where c.contacts_id=tm.contactsid and tm.typeid=?)");
        Cursor cursor = database.rawQuery(sqlStr.toString(), new String[]{typeId + ""});
        List<MyContact> mcList= new ArrayList<MyContact>();
        int count = cursor.getCount();
        if(count <= 0){
            return null;
        }
        for(int i = 0; i < count; i++){
            cursor.moveToPosition(i);
            int contactsId = cursor.getInt(0);
            String name = cursor.getString(1);
            String phone= cursor.getString(2);
            MyContact mc = new MyContact();
            mc.setContactsId(contactsId);
            mc.setName(name);
            mc.setMobilePhone(phone);
            mcList.add(mc);
        }
        return mcList;
    }

    public List<MyContact> getContactsByGroupId(int groupId) {
        SQLiteDatabase database = manager.getWritableDatabase();
        StringBuilder sqlStr = new StringBuilder();
        sqlStr.append("select c.contacts_id ,c.name,c.mobile_phone");
        sqlStr.append(" from " + DBInitScript.Table_ContactsInfo + " c");
        sqlStr.append(" where exists (select 1 from " + DBInitScript.Table_Group_Middle + " gm where c.contacts_id=gm.contactsid and gm.groupid=?)");
        Cursor cursor = database.rawQuery(sqlStr.toString(), new String[]{groupId + ""});
        List<MyContact> mcList= new ArrayList<MyContact>();
        int count = cursor.getCount();
        if(count <= 0){
            return null;
        }
        for(int i = 0; i < count; i++){
            cursor.moveToPosition(i);
            int contactsId = cursor.getInt(0);
            String name = cursor.getString(1);
            String phone= cursor.getString(2);
            MyContact mc = new MyContact();
            mc.setContactsId(contactsId);
            mc.setName(name);
            mc.setMobilePhone(phone);
            mcList.add(mc);
        }
        return mcList;
    }

}
